// Copyright 2010 Google Inc. All Rights Reserved.

package com.google.zahra.webmanager;

import com.google.zahra.testmanager.Test;
import com.google.zahra.util.Util;

import org.terracotta.workmanager.pipemanager.Pipe;
import org.terracotta.workmanager.pipemanager.PipeManager;
import org.terracotta.workmanager.queue.Queue;
import org.terracotta.workmanager.routing.RoutableWorkItem;

import java.io.IOException;
import java.util.Iterator;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author arthurkok@google.com (Your Name Here)
 *
 */
public class WorkerServlet extends HttpServlet {

  static final PipeManager<String> pipeManager = WebManager.PIPE_MANAGER;

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException {

    String workerId = request.getParameter("workerId");
    response.setContentType("text/html");
    response.setStatus(HttpServletResponse.SC_OK);
    
    StringBuffer bodyString = new StringBuffer();

    if (pipeManager.getWorkerOs(workerId) == -1) {
      bodyString.append("Worker does not exist");
    } else {

      // Worker pending queue
      bodyString.append("<h2>Pending Tests for " + workerId + "</h2>");
      
      bodyString.append(
          "<FORM ACTION='/workerInfo' METHOD='POST'>" 
              + "<TABLE><input type='hidden' name='workerId' value='" + workerId +"'>"
              + "<TR><TH id='submit'>Command</TH><TD><INPUT TYPE='TEXT' NAME='command' SIZE=40></TD>"                
              + "<TD><INPUT TYPE='SUBMIT' VALUE='Submit Command'></TD></TR>" 
              + "</TABLE>" + "</FORM>");     
      
      bodyString.append("<table>");
      bodyString.append(
              String
                  .format("<table border='1'><tr><th>%s</th><th>%s</th><th>%s</th><th>%s</th><th>%s</th></tr>",
                      "Job ID",
                      "Time Created",
                      "Test Name",
                      "OS",
                      "Retries"));

      Pipe<RoutableWorkItem<String>, String> pipe = pipeManager.get(workerId);

      if (pipe != null) {
        Queue<RoutableWorkItem<String>> queue = pipe.getPendingWorkQueue();

        for (Iterator<RoutableWorkItem<String>> it = queue.iterator(); it.hasNext();) {

          // Need to fix concurrency issue.
          RoutableWorkItem<String> workItem = it.next();
          Test test = (Test) workItem.getResult();
          String output =
              "<td><a href='/viewTest?jobId=" + test.jobID + "'>" + test.jobID + "</a></td>";
          output += "<td>" + workItem.getTimeCreated() + "</td>";
          output += "<td>" + test.name + "</td>";
          output += "<td>" + Util.getOsName(test.os) + "</td>";
          output += "<td>" + test.retries + "</td></tr>";

          bodyString.append(output);

        }

        bodyString.append("</table><br/>");
      }
    }
    
    response.getWriter().print(Util.getHTML(bodyString.toString(), "Zahra - Worker"));

  }

  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    
    StringBuffer bodyString = new StringBuffer();
    String workerId = request.getParameter("workerId");
    String command = request.getParameter("command");
    response.setContentType("text/html");
    response.setStatus(HttpServletResponse.SC_OK);

    if (command == null || command == "") {
      bodyString.append("No command entered!");
    }
    else {      
      try {
        pipeManager.sendCommand(workerId, command);
      } catch (InterruptedException e) {
          Thread.currentThread().interrupt();
      }
      if (Thread.interrupted()) {
        bodyString.append("Error sending command: Thread was interrupted!");
      }
      else {
        bodyString.append("Sent command: '" + command + "' to "+ workerId +" successfully!");
      }
    }

    response.getWriter().print(Util.getHTML(bodyString.toString(), "Zahra - Submit new Test"));
  }
}
